package com.zhongwang.mms.module.tool.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.zhongwang.mms.gen.entity.*;
import com.zhongwang.mms.module.buy.model.ReportPlanModel;
import com.zhongwang.mms.module.system.log.LogService;
import com.zhongwang.mms.module.tool.callback.EquipmentCallBack;
import com.zhongwang.mms.module.tool.dao.EquipmentDao;
import com.zhongwang.mms.module.tool.listner.EquipmentListener;
import com.zhongwang.mms.module.tool.model.EquipmentModel;
import com.zhongwang.mms.module.tool.model.ReportEquipmentModel;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;


/**
 * 设备台账
 * @Author: 闫薇
 */
@Service
public class EquipmentService {
    @Autowired
    private EquipmentDao equipmentDao;
    //声明变量
    private String msg = "";

    @Value("${user.upload.path}")
    private String uploadPath;

    @Autowired
    private LogService logService;

    /**
     * 查询设备台账信息
     *
     * @param model 设备台账参数
     * @return EquipmentModel
     */
    public List<EquipmentModel> selectAccEquipmentList(EquipmentModel model) {
        return equipmentDao.selectAccEquipmentList(model);
    }

    /**
     * 导入日报
     *
     * @param file 导入文件
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public String importFile(MultipartFile file,String eqmMonth) {

        try {
            //固定第一个sheet：AB类
            EasyExcel.read(file.getInputStream(), ReportEquipmentModel.class, new EquipmentListener(equipmentDao,"AB类",eqmMonth, new EquipmentCallBack() {
                @Override
                public void onSuccess() {
                    msg = "导入完成";
                }

                @Override
                public void onWarning(List<ReportEquipmentModel> reportEquipmentModels) {
                    msg = "部份数据无法导入，请点击下载检查数据内容";
                    exportErrorExcel(reportEquipmentModels);
                }

                @Override
                public void onError() {
                    msg = "文件内容有误，导入失败";
                }
            })).headRowNumber(4).sheet(0).doRead();

            //固定第二个sheet：C类
            EasyExcel.read(file.getInputStream(), ReportEquipmentModel.class, new EquipmentListener(equipmentDao,"C类",eqmMonth, new EquipmentCallBack() {
                @Override
                public void onSuccess() {
                    msg = "导入完成";
                }

                @Override
                public void onWarning(List<ReportEquipmentModel> reportEquipmentModels) {
                    msg = "部份数据无法导入，请点击下载检查数据内容";
                    exportErrorExcel(reportEquipmentModels);
                }

                @Override
                public void onError() {
                    msg = "文件内容有误，导入失败";
                }
            })).headRowNumber(4).sheet(1).doRead();


            //固定第三个sheet：焊机
            EasyExcel.read(file.getInputStream(), ReportEquipmentModel.class, new EquipmentListener(equipmentDao,"焊机",eqmMonth, new EquipmentCallBack() {
                @Override
                public void onSuccess() {
                    msg = "导入完成";
                }

                @Override
                public void onWarning(List<ReportEquipmentModel> reportEquipmentModels) {
                    msg = "部份数据无法导入，请点击下载检查数据内容";
                    exportErrorExcel(reportEquipmentModels);
                }

                @Override
                public void onError() {
                    msg = "文件内容有误，导入失败";
                }
            })).headRowNumber(4).sheet(2).doRead();

            //固定第四个sheet：特种车辆
            EasyExcel.read(file.getInputStream(), ReportEquipmentModel.class, new EquipmentListener(equipmentDao,"特种车辆",eqmMonth, new EquipmentCallBack() {
                @Override
                public void onSuccess() {
                    msg = "导入完成";
                }

                @Override
                public void onWarning(List<ReportEquipmentModel> reportEquipmentModels) {
                    msg = "部份数据无法导入，请点击下载检查数据内容";
                    exportErrorExcel(reportEquipmentModels);
                }

                @Override
                public void onError() {
                    msg = "文件内容有误，导入失败";
                }
            })).headRowNumber(4).sheet(3).doRead();

            //固定第五个sheet：特种车辆
            EasyExcel.read(file.getInputStream(), ReportEquipmentModel.class, new EquipmentListener(equipmentDao,"特种车辆",eqmMonth, new EquipmentCallBack() {
                @Override
                public void onSuccess() {
                    msg = "导入完成";
                }

                @Override
                public void onWarning(List<ReportEquipmentModel> reportEquipmentModels) {
                    msg = "部份数据无法导入，请点击下载检查数据内容";
                    exportErrorExcel(reportEquipmentModels);
                }

                @Override
                public void onError() {
                    msg = "文件内容有误，导入失败";
                }
            })).headRowNumber(4).sheet(4).doRead();

        } catch (IOException e) {
            return "导入失败";
        }
        logService.saveLog("设备台账编辑", "导入设备台账");
        return msg;
    }
    /**
     * 异常数据导出到Excel
     *
     * @param errorList
     */
    private void exportErrorExcel(List<ReportEquipmentModel> errorList) {
        if (errorList.size() <= 0) {
            return;
        }
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        // 取得错误数据
        String path = uploadPath + user.getAccount() + "/";
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        path = path + "EquipmentError.xls";
        // 头的策略
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontHeightInPoints((short) 10);
        headWriteCellStyle.setWriteFont(headWriteFont);
        // 内容的策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
        HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);

        // 这里 需要指定写用哪个class去读，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
        EasyExcel.write(path, ReportEquipmentModel.class).registerWriteHandler(horizontalCellStyleStrategy).sheet("未成功导入数据")
                .doWrite(errorList);

    }

    /**
     * 删除
     * @param empId 主键id
     * @return
     */
    public Integer del(Integer empId){
        return equipmentDao.del(empId);
    }

    /**
     * 根据输入的厂内编号，判断数据是不是唯一。
     * @param keyModel
     * @return
     */
    public ReportEquipmentModel selectAccEquipment(ReportEquipmentModel keyModel){
        return equipmentDao.selectAccEquipment(keyModel);
    }
    /**
     * 修改
     * @param data 实体信息
     * @return
     */
    public Integer update(ReportEquipmentModel data)
    {
        return equipmentDao.update(data);
    }

    /**
     * 获取数据库中最大的排序号
     * @return
     */
    public Integer selectMaxNum(){
        return equipmentDao.selectMaxNum();
    }

    /**
     * 新增数据
     * @param data
     * @return
     */
    public Integer insert(ReportEquipmentModel data)
    {
        return equipmentDao.insert(data);
    }

    /**
     * 验证同一主键的是否存在
     * @param model EquipmentModel
     * @return
     */
    public List<EquipmentModel> findByCode(EquipmentModel model){
        return equipmentDao.findByCode(model);
    }

    /**
     * 判断文件是否存在
     *
     * @param url 文件URL
     * @return 是否存在
     */
    public boolean exist(String url) {
        int i = url.lastIndexOf("files/");
        String path = uploadPath + url.substring(i + 6);
        File file = new File(path);
        if (!file.exists()) {
            return false;
        }
        return true;
    }

    /**
     * 查询设备类型
     * @return
     */
    public List<EquipmentModel> selectAccEquipmentType(){
        return equipmentDao.selectAccEquipmentType();
    }

}
